<?php
/**
 * 食材控制器
 * 处理食材查询、分类、搜索等
 */

class FoodController {
    private $db;
    
    public function __construct() {
        $database = Database::getInstance();
        $this->db = $database->getConnection();
    }
    
    /**
     * 获取食材列表
     */
    public function getFoodList($data) {
        try {
            $page = isset($data['page']) ? max(1, intval($data['page'])) : 1;
            $pageSize = isset($data['pageSize']) ? max(1, intval($data['pageSize'])) : 20;
            $categoryId = isset($data['categoryId']) ? intval($data['categoryId']) : null;
            
            $offset = ($page - 1) * $pageSize;
            
            $sql = "SELECT f.*, c.name as category_name FROM foods f LEFT JOIN categories c ON f.category_id = c.id WHERE f.status = 1";
            $params = [];
            
            if ($categoryId) {
                $sql .= " AND f.category_id = ?";
                $params[] = $categoryId;
            }
            
            $sql .= " ORDER BY f.created_at DESC LIMIT ? OFFSET ?";
            $params[] = $pageSize;
            $params[] = $offset;
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            $foods = $stmt->fetchAll();
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM foods f WHERE f.status = 1";
            $countParams = [];
            
            if ($categoryId) {
                $countSql .= " AND f.category_id = ?";
                $countParams[] = $categoryId;
            }
            
            $countStmt = $this->db->prepare($countSql);
            $countStmt->execute($countParams);
            $total = $countStmt->fetch()['total'];
            
            // 格式化食材数据
            $formattedFoods = array_map(function($food) {
                return [
                    'id' => $food['id'],
                    'name' => $food['name'],
                    'image' => $food['image'],
                    'category' => $food['category_name'],
                    'calories' => $food['calories'],
                    'protein' => $food['protein'],
                    'carbohydrate' => $food['carbohydrate'],
                    'fat' => $food['fat'],
                    'sugar' => $food['sugar'],
                    'purine' => $food['purine'],
                    'fiber' => $food['fiber'],
                    'suitableFor' => json_decode($food['suitable_for'], true) ?: [],
                    'description' => $food['description']
                ];
            }, $foods);
            
            return apiSuccess([
                'list' => $formattedFoods,
                'pagination' => [
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'total' => $total,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 搜索食材
     */
    public function searchFood($data) {
        try {
            validateParams($data, ['keyword']);
            
            $keyword = '%' . $data['keyword'] . '%';
            $page = isset($data['page']) ? max(1, intval($data['page'])) : 1;
            $pageSize = isset($data['pageSize']) ? max(1, intval($data['pageSize'])) : 20;
            $offset = ($page - 1) * $pageSize;
            
            $sql = "SELECT f.*, c.name as category_name FROM foods f LEFT JOIN categories c ON f.category_id = c.id WHERE f.status = 1 AND (f.name LIKE ? OR f.description LIKE ?)";
            $params = [$keyword, $keyword];
            
            // 添加健康条件筛选
            if (isset($data['healthCondition'])) {
                $healthCondition = $data['healthCondition'];
                $sql .= " AND JSON_CONTAINS(f.suitable_for, ?)";
                $params[] = json_encode([$healthCondition]);
            }
            
            $sql .= " ORDER BY f.created_at DESC LIMIT ? OFFSET ?";
            $params[] = $pageSize;
            $params[] = $offset;
            
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            $foods = $stmt->fetchAll();
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM foods f WHERE f.status = 1 AND (f.name LIKE ? OR f.description LIKE ?)";
            $countParams = [$keyword, $keyword];
            
            if (isset($data['healthCondition'])) {
                $countSql .= " AND JSON_CONTAINS(f.suitable_for, ?)";
                $countParams[] = json_encode([$data['healthCondition']]);
            }
            
            $countStmt = $this->db->prepare($countSql);
            $countStmt->execute($countParams);
            $total = $countStmt->fetch()['total'];
            
            $formattedFoods = array_map(function($food) {
                return [
                    'id' => $food['id'],
                    'name' => $food['name'],
                    'image' => $food['image'],
                    'category' => $food['category_name'],
                    'calories' => $food['calories'],
                    'protein' => $food['protein'],
                    'carbohydrate' => $food['carbohydrate'],
                    'fat' => $food['fat'],
                    'sugar' => $food['sugar'],
                    'purine' => $food['purine'],
                    'fiber' => $food['fiber'],
                    'suitableFor' => json_decode($food['suitable_for'], true) ?: [],
                    'description' => $food['description']
                ];
            }, $foods);
            
            return apiSuccess([
                'list' => $formattedFoods,
                'pagination' => [
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'total' => $total,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 获取食材详情
     */
    public function getFoodDetail($data) {
        try {
            validateParams($data, ['id']);
            
            $stmt = $this->db->prepare("SELECT f.*, c.name as category_name FROM foods f LEFT JOIN categories c ON f.category_id = c.id WHERE f.id = ? AND f.status = 1");
            $stmt->execute([$data['id']]);
            $food = $stmt->fetch();
            
            if (!$food) {
                return apiError('食材不存在');
            }
            
            $foodDetail = [
                'id' => $food['id'],
                'name' => $food['name'],
                'image' => $food['image'],
                'category' => $food['category_name'],
                'calories' => $food['calories'],
                'protein' => $food['protein'],
                'carbohydrate' => $food['carbohydrate'],
                'fat' => $food['fat'],
                'sugar' => $food['sugar'],
                'purine' => $food['purine'],
                'fiber' => $food['fiber'],
                'vitamins' => json_decode($food['vitamins'], true) ?: [],
                'minerals' => json_decode($food['minerals'], true) ?: [],
                'suitableFor' => json_decode($food['suitable_for'], true) ?: [],
                'avoidFor' => json_decode($food['avoid_for'], true) ?: [],
                'cookingTips' => $food['cooking_tips'],
                'description' => $food['description'],
                'nutritionalValue' => $food['nutritional_value']
            ];
            
            return apiSuccess($foodDetail);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 获取分类列表
     */
    public function getCategories($data) {
        try {
            $stmt = $this->db->prepare("SELECT * FROM categories WHERE status = 1 ORDER BY sort_order ASC");
            $stmt->execute();
            $categories = $stmt->fetchAll();
            
            $formattedCategories = array_map(function($category) {
                return [
                    'id' => $category['id'],
                    'name' => $category['name'],
                    'icon' => $category['icon'],
                    'description' => $category['description']
                ];
            }, $categories);
            
            return apiSuccess($formattedCategories);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
}

?>